//
//  WEXRefreshControl.swift
//  microBlog
//
//  Created by apple on 16/4/23.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit


enum WEXRefreshControlState: Int {
    case Normal = 0//"默认"
    case Pulling = 1//"松手就去刷新的状态"
    case Refreshing = 2//"刷新中的状态"
}

private let refreshHeight: CGFloat = 50

class WEXRefreshControl: UIControl {
    
//    刷新状态
    var refreshStatus: WEXRefreshControlState = .Normal {
        
        didSet{
            
            switch refreshStatus {
                
            case .Pulling:
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
//                    设置箭头旋转
                    self.igv_arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                self.lb_message.text = "准备加载"
                

            case .Refreshing:
//                设置箭头隐藏
                self.igv_arrowImage.hidden = true
                
//                菊花转动
                self.indecatorView.startAnimating()
                
//                设置文字
                self.lb_message.text = "努力加载中"
                
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + refreshHeight
                })
                
//                去调用刷新方法
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            case .Normal:
//                菊花停止转动，因为菊花不转动默认隐藏，所以可以不用隐藏菊花
                self.indecatorView.stopAnimating()
                
//                设置文字
                self.lb_message.text = "等待加载"
                
//                显示箭头，并且朝下
                self.igv_arrowImage.hidden = false
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    
                    self.igv_arrowImage.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - refreshHeight
                    })
                }
            }
            
        }
    }
    
    var tableView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI(){
        
        self.frame.size.height = refreshHeight
        
        self.frame.origin.y = -refreshHeight
        
        backgroundColor = UIColor.brownColor()
        
        
//        添加子控件
        addSubview(igv_arrowImage)
        addSubview(lb_message)
        addSubview(indecatorView)
        
        
        // 设置箭头图片的约束
        igv_arrowImage.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self).offset(-50)
            make.centerY.equalTo(self)

        }
        // 设置信息的约束
        lb_message.snp_makeConstraints { (make) -> Void in
        
            make.centerY.equalTo(igv_arrowImage)
            make.leading.equalTo(igv_arrowImage.snp_trailing)
        }
        // 设置菊花的约束
        indecatorView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(igv_arrowImage)
        }
        
        
        
    }
    
    // MARK: - 供外界调用的停止刷新的方法
    func endRefreshing(){
        
        refreshStatus = .Normal
        
    }
    
    // MARK: - 获取父类的view
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
            
            return
        }
        // 给tableView赋值
        self.tableView = tableView as? UIScrollView
        self.frame.size.width = tableView.frame.size.width
        
//        使用kvo监听
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        
    }
    
    // MARK: - 监听调用的方法
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffset = self.tableView?.contentOffset
        
        let conditionValue = -tableView!.contentInset.top - refreshHeight
//        如果用户正在拖拽
        if tableView!.dragging {
//            如果此时tableView的偏移小于默认偏移量加上刷新控件本身高度，并且刷新状态处于等待刷新状态
            if contentOffset?.y < conditionValue && refreshStatus == .Normal {
                
                
//                print(conditionValue)
//                设置状态更改为准备刷新
                refreshStatus = .Pulling
                
            }else{
//                如果此时tableView的偏移大于默认偏移量加上自身高度，并且刷新状态处于准备刷新状态
            if contentOffset?.y >= conditionValue && refreshStatus == .Pulling {
                
//                print(conditionValue)
//                设置状态更改为等待刷新状态
                refreshStatus = .Normal
                }
        }
        
//        如果用户松手
        }else{
//            并且此时的刷新状态为准备刷新
            if refreshStatus == .Pulling{
//                设置状态改为刷新
                refreshStatus = .Refreshing
            }
        }
    }
    
    // MARK: - 移除监听事件
    deinit{
        
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // MARK: - 懒加载
    // 箭头图片
    private lazy var igv_arrowImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 提示
    private lazy var lb_message: UILabel = {
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), textFont: 12)
        
        label.text = "等待加载"
        
        return label
    }()
    
    // 菊花
    private lazy var indecatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    
}
